<template>
  <Dialog
    :funcConfirm="handleConfirm"
    :funcCancel="handleClose"
    :headerTitle="headerTitle"
    :confirmTitle="confirmTitle"
    :open="open"
  >
    <template v-slot:body>
      <div class="content-wrapper">
        <div class="content-row">
          <div class="row-name">
            <span class="name-required">{{ "*" }}</span>
            <span class="name-text">{{ "名 称：" }}</span>
          </div>
          <div class="input-box">
            <input
              type="text"
              v-model="params.name"
              maxlength="20"
              minlength="2"
              placeholder
            />
          </div>
        </div>
        <div class="content-row">
          <div class="row-name">
            <span class="name-required">{{ "*" }}</span>
            <span class="name-text">{{ "图 标：" }}</span>
          </div>
          <div class="image-box">
            <div
              class="image-grid"
              v-for="image of images"
              :key="image.id"
              :class="{ active: selectedIcon == image }"
              @click="selectedIcon = image"
            >
              <img class="image-item" :src="image.url" />
              <img
                class="image-selected"
                v-if="selectedIcon == image"
                src="@media/expo/icon-select@2x.png"
              />
            </div>
          </div>
        </div>
        <div class="content-row">
          <div class="row-name">
            <span class="name-required">{{ "*" }}</span>
            <span class="name-text">{{ "类 型：" }}</span>
          </div>
          <div class="input-box">
            <input
              type="text"
              :value="typeItems[params.type]"
              maxlength="20"
              minlength="2"
              readonly="readonly"
              placeholder="【上传文件后自动识别】"
            />
          </div>
        </div>
        <div class="content-row">
          <div class="row-name">
            <span class="name-required">{{ "*" }}</span>
            <span class="name-text">{{ "文 件：" }}</span>
          </div>
          <div class="media-row">
            <div class="media-name-content">
              <span class="media-name">{{ params.media.name }}</span>
            </div>
            <button class="pickup-button" @click="handlePickupMedia">
              {{ "选择文件" }}
            </button>
            <input
              ref="fileInput"
              type="file"
              class="upload-input"
              @change="handleFile"
            />
          </div>
        </div>
        <img id="imgCover" src="@/assets/common/mark.png" class="clip" />
      </div>
    </template>
  </Dialog>
</template>

<script>
import oss from "@/utils/oss";
import { randomString, $formatDate } from "@/utils/tools";
import expoModuleService from "@api/expoModuleService";
import Dialog from "@/component/dialog/Dialog";
import { Loading, Message } from "element-ui";
import { degrees, PDFDocument, rgb, StandardFonts } from "pdf-lib";
export default {
  components: { Dialog },
  props: {
    funcConfirm: Function,
  },
  data() {
    return {
      headerTitle: "",
      confirmTitle: "",
      images: [],
      selectedIcon: {},
      params: {
        type: null,
      },
      typeItems: {
        null: "",
        1: "视频",
        2: "PPT",
        3: "图片",
        4: "Excel",
        5: "PDF",
      },
      imgsrc: null,
      pdfBytes: null,
    };
  },
  // 监听属性 类似于data概念
  computed: {
    open() {
      const isOpen =
        this.$store.state.dialog.isOpenCreateModule ||
        this.$store.state.dialog.isOpenEditModule;
      return isOpen;
    },
    isCreate() {
      return this.$store.state.dialog.isOpenCreateModule;
    },
  },
  // 监控data中的数据变化
  watch: {
    open(value) {
      if (!value) {
        return;
      }
      if (this.isCreate) {
        this.headerTitle = "新建模块";
        this.confirmTitle = "创建";
        const item = this.$store.state.dialog.createModuleItem;
        this.params = {
          type: null,
          name: "",
          expo_uid: item.expo_uid,
          media: {},
          sort: item.sort,
          image: "",
          parent_uid: "",
          media_size: "0",
        };
      } else {
        this.headerTitle = "编辑模块";
        this.confirmTitle = "完成";
        const item = this.$store.state.dialog.editModuleItem;
        this.params = {
          type: item.type,
          name: item.name,
          expo_uid: item.uid,
          media: {
            name: item.media.replace(/^[\S\s]*\//, ""),
            media: item.media,
          },
          sort: item.sort,
          image: item.image,
          uid: item.uid,
          media_size: item.media_size,
        };
      }
    },
    params(value) {
      if (value.image !== undefined && value.image !== "") {
        const imageIndex = this.images.findIndex((item) => {
          return item.url === value.image;
        });

        this.selectedIcon = this.images[imageIndex];
      }
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.fetchImages();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    handleClose() {
      const commitType = this.isCreate
        ? "dialog/CREATE_MODULE_OPEN"
        : "dialog/EDIT_MODULE_OPEN";
      this.$store.commit(commitType, false);
      this.selectedIcon = this.images[0];
    },
    handleConfirm() {
      if (!this.params.name) {
        Message.warning("请输入名称");

        return;
      }
      // const a=true1

      // JSON.stringify(this.params.media) == "{}"
      if (this.params.media.name === undefined) {
        Message.warning("请选择文件");
        return;
      }
      if (this.isCreate) {
        this.createModule();
        return;
      } else {
        this.editModule();
      }
    },
    fetchImages() {
      expoModuleService
        .getCreateImage()
        .then((res) => {
          this.images = res.data.data;
          const defaultImage = this.images[0];
          if (defaultImage) {
            this.selectedIcon = defaultImage;
          }
        })
        .catch((res) => {});
    },
    editModule() {
      this.params.image = this.selectedIcon.url;
      const originItem = this.$store.state.dialog.editModuleItem;
      let isEdit = false;
      let formData = new FormData();
      if (this.params.type) {
        isEdit = true;
        formData.append("type", this.params.type);
      }
      if (this.params.name) {
        isEdit = true;
        formData.append("name", this.params.name);
      }
      if (this.params.image) {
        isEdit = true;
        formData.append("image", this.params.image);
      }

      if (this.params.media.size) {
        isEdit = true;

        const file = this.params.media;
        const path = this.getUploadFilePath();

        let loadingInstance = Loading.service({
          fullscreen: true,
          background: "rgba(0, 0, 0, 0.2)",
        });

        if (this.params.type === 3) {
          this.imgTogether(this.imgsrc, (url) => {
            const markFile = this.dataURLtoFile(url, file.name);
            this.editoss(path, markFile, loadingInstance, formData);
          });
        } else if (this.params.type === 5) {
          this.pdfBytes = "data:application/pdf;base64," + this.pdfBytes;
          const markFile = this.pdfURLtoFile(this.pdfBytes, file.name);
          this.editoss(path, markFile, loadingInstance, formData);
        } else {
          this.editoss(path, file, loadingInstance, formData);
        }
        return;
      } else {
        console.log(
          123,
          this.params.media.media.slice(
            this.params.media.media.indexOf("resources")
          )
        );
        formData.append(
          "media",
          this.params.media.media.slice(
            this.params.media.media.indexOf("resources")
          )
        );
        formData.append("media_size", this.params.media_size);
      }
      if (!isEdit) {
        this.handleClose();
        return;
      }
      this.requestEditModule(formData);
    },
    requestEditModule(formData, loadingInstance) {
      if (!loadingInstance) {
        loadingInstance = Loading.service({
          fullscreen: true,
          background: "rgba(0, 0, 0, 0.2)",
        });
      }
      const level = "CHILD";
      formData.append("uid", this.params.uid);

      expoModuleService
        .editModule(level, formData)
        .then((res) => {
          this.funcConfirm();
          this.handleClose();
          this.$nextTick(() => {
            loadingInstance.close();
          });
        })
        .catch((res) => {
          this.$nextTick(() => {
            loadingInstance.close();
          });
        });
    },
    getUploadFilePath() {
      const file = this.params.media;
      const date = $formatDate(new Date(), "yyyy-MM-dd");
      const fileTypes = ["", "video", "ppt", "image", "excel", "pdf"];
      let fileType = fileTypes[this.params.type];
      const fileName = randomString(10);
      const path = `resources/${date}/${fileType}/${fileName}.${file.name
        .split(".")
        .slice(-1)}`;
      return path;
    },
    createModule() {
      const file = this.params.media;
      const path = this.getUploadFilePath();

      let loadingInstance = Loading.service({
        fullscreen: true,
        background: "rgba(0, 0, 0, 0.2)",
      });
      console.log(54324, this.params.type);
      // 加上水印
      if (this.params.type === 3) {
        this.imgTogether(this.imgsrc, (url) => {
          const markFile = this.dataURLtoFile(url, file.name);
          this.createoss(path, markFile, loadingInstance);
        });
      } else if (this.params.type === 5) {
        this.pdfBytes = "data:application/pdf;base64," + this.pdfBytes;
        const markFile = this.pdfURLtoFile(this.pdfBytes, file.name);
        this.createoss(path, markFile, loadingInstance);
      } else {
        this.createoss(path, file, loadingInstance);
      }
    },
    // canvas 图片合成
    imgTogether(url, callback) {
      const canvas = document.createElement("canvas");
      const eleImgCover = document.getElementById("imgCover");
      const context = canvas.getContext("2d");
      const percentage = parseFloat(process.env.VUE_APP_PERCENTAG)
      // 这是上传图像
      const imgUpload = new Image();
      imgUpload.onload = function () {
        canvas.width = imgUpload.width;
        canvas.height = imgUpload.height;
        // 绘制
        context.drawImage(
          imgUpload,
          0,
          0,
          canvas.width,
          canvas.height,
          0,
          0,
          canvas.width,
          canvas.height
        );
        console.log(percentage,typeof percentage);
        // 再次绘制
        context.drawImage(
          eleImgCover,
          (canvas.width - (canvas.width * percentage)) / 2,
          (canvas.height -
            (canvas.width * percentage) * (eleImgCover.height / eleImgCover.width)) /
            2,
          canvas.width * percentage,
          (canvas.width * percentage) * (eleImgCover.height / eleImgCover.width)
        );
        // 回调
        callback(canvas.toDataURL("image/png"));
      };
      imgUpload.src = url;
    },
    dataURLtoFile(dataurl, filename) {
      // 获取到base64编码
      const arr = dataurl.split(",");
      // 将base64编码转为字符串
      const bstr = window.atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n); // 创建初始化为0的，包含length个元素的无符号整型数组
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: "image/png",
      });
    },
    pdfURLtoFile(dataurl, filename) {
      // 获取到base64编码
      const arr = dataurl.split(",");
      // 将base64编码转为字符串
      const bstr = window.atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n); // 创建初始化为0的，包含length个元素的无符号整型数组
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: "application/pdf",
      });
    },
    requestCreatModule(path, loadingInstance) {
      this.params.image = this.selectedIcon.url;
      this.params.media_size = this.params.media.size;
      let formData = new FormData();
      formData.append("type", this.params.type);
      formData.append("name", this.params.name);
      formData.append("expo_uid", this.params.expo_uid);
      formData.append("media", path);
      formData.append("sort", this.params.sort);
      formData.append("image", this.params.image);
      formData.append(
        "parent_uid",
        JSON.parse(localStorage.getItem("query")).uid
      );
      formData.append("media_size", this.params.media_size);

      expoModuleService
        .createModule(formData)
        .then((res) => {
          this.funcConfirm();
          this.handleClose();
          this.$nextTick(() => {
            loadingInstance.close();
          });
        })
        .catch((res) => {
          this.$nextTick(() => {
            loadingInstance.close();
          });
        });
    },
    handlePickupMedia() {
      this.$refs.fileInput.dispatchEvent(new MouseEvent("click"));
    },
    handleFile() {
      const inputFile = this.$refs.fileInput.files[0];
      if (!inputFile) {
        return;
      }

      if (inputFile.type.indexOf("video") > -1) {
        this.params.type = 1;
      } else if (inputFile.type.indexOf("image") > -1) {
        this.params.type = 3;
        let reader = new FileReader();
        reader.readAsDataURL(inputFile);
        reader.onload = (e) => {
          this.imgsrc = e.target.result;
          console.log(this.imgsrc);
        };
      } else if (inputFile.name.indexOf(".ppt") > -1) {
        this.params.type = 2;
      } else if (
        inputFile.name.indexOf(".pdf") > -1 ||
        inputFile.name.indexOf(".PDF") > -1
      ) {
        this.params.type = 5;
        this.pdfwater(inputFile);
      } else if (
        inputFile.name.indexOf(".xlsx") > -1 ||
        inputFile.name.indexOf(".xls") > -1
      ) {
        this.params.type = 4;
      } else {
        Message.warning("不支持文件类型");
        return;
      }
      this.params.media = inputFile;
      console.log(3);
    },
    pdfwater(inputFile) {
      let reader = new FileReader();

      let loadingInstance = Loading.service({
        fullscreen: true,
        background: "rgba(0, 0, 0, 0.2)",
      });
      console.log(2);
      reader.readAsDataURL(inputFile);
      reader.onload = async (e) => {
        this.imgsrc = e.target.result;
        const pdfDoc = await PDFDocument.load(this.imgsrc);
        const pages = pdfDoc.getPages();
        const percentage = parseFloat(process.env.VUE_APP_PERCENTAG)
        const img =
          "https://ydyjy-oss.devotedigital.cn/resources/mark/pdf_mark.png";
        const ImgCover = await fetch(img).then((res) => res.arrayBuffer());
        const eleImgCover = await pdfDoc.embedPng(ImgCover);
        pages.forEach((item) => {
          item.drawImage(eleImgCover, {
            x: (item.getWidth()-(item.getWidth() * percentage)) / 2,
            y: (item.getHeight() - ((item.getWidth() * percentage) * (eleImgCover.height/eleImgCover.width))) / 2,
            width: item.getWidth() * percentage,
            height: (item.getWidth() * percentage) * (eleImgCover.height/eleImgCover.width),
          });
        });
        loadingInstance.close();
        this.params.media = inputFile;
        this.pdfBytes = await pdfDoc.saveAsBase64();
        // 本地浏览pdf
        // const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
        // window.open(pdfDataUri)
      };
    },
    createoss(path, file, loadingInstance) {
      oss.client
        .put(path, file, { timeout: 600000 })
        .then((res) => {
          this.requestCreatModule(path, loadingInstance);
        })
        .catch((err) => {
          this.$nextTick(() => {
            loadingInstance.close();
          });
          this.$message.warning("文件上传失败，请重试");
        });
    },
    editoss(path, file, loadingInstance, formData) {
      oss.client
        .put(path, file, { timeout: 600000 })
        .then((res) => {
          formData.append("media", path);

          formData.append("media_size", this.params.media.size);
          this.requestEditModule(formData, loadingInstance);
        })
        .catch((err) => {
          this.$nextTick(() => {
            loadingInstance.close();
          });

          this.$message.warning("文件上传失败，请重试");
        });
    },
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="scss">
@import "@/style/scss/component/dialog/createModuleDialog.scss";
</style>
<style scoped lang="scss">
.clip {
  position: absolute;
  clip: rect(0 0 0 0);
}
</style>
